package com.legendshop.openportal.sdk.client.http.analyzer;

import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.legendshop.openportal.sdk.client.http.HttpResponseAnalyzer;
import com.legendshop.openportal.sdk.client.http.HttpResponseAnalyzerContext;
import com.legendshop.openportal.sdk.model.OpenResult;
import com.legendshop.openportal.sdk.model.constants.CommonStatusEnum;
import com.legendshop.openportal.sdk.model.BaseResponse;
import com.legendshop.openportal.sdk.utils.ConvertUtil;

import java.lang.reflect.Type;

/**
 * @author jzh
 * @version 1.0.0
 * @title ErrorResponseAnalyzer
 * @date 2024/6/18 16:51
 * @description：异常响应解析器
 */
public class ErrorResponseAnalyzer implements HttpResponseAnalyzer {

    private static final ErrorResponseAnalyzer INSTANCE = new ErrorResponseAnalyzer();

    private ErrorResponseAnalyzer() {

    }

    public static ErrorResponseAnalyzer getInstance() {
        return INSTANCE;
    }

    @Override
    public <T> OpenResult<T> analyze(HttpResponse httpResponse, Type responseClass) {
        JSONObject jsonObject = HttpResponseAnalyzerContext.get();
        if (!httpResponse.isOk()) {
            if (jsonObject != null) {
                return ConvertUtil.convert2OpenResult(jsonObject, responseClass);
            }
            return OpenResult.fail(CommonStatusEnum.ERROR, httpResponse.body());
        }

        if (jsonObject == null) {
            return OpenResult.fail(CommonStatusEnum.UNABLE_ANALYZER, httpResponse.body());
        }

        return null;
    }
}
